package com.evision.webcrawler.baidu.url;

import com.evision.webcrawler.baidu.RequestUrl;
import org.apache.log4j.Logger;

import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * 
 * @author xiang
 * Baidu图搜请求链接生成器
 * 拼接百度图像请求信息
 * 
 */
public class BaiduUrlProducer implements Runnable{
	private String baseUrl = "http://image.baidu.com/search/index?";//基础URL
	private int defaultPageSize = 60;								//默认取图数量
	private String defaultParam = "tn=resultjson&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&"
							+ "fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&"
							+ "height=&face=0&istype=2&ie=utf-8&oq=test&rsp=-1&";								//固定参数
	private String wordName = "word";								//查询关键词参数名称
	private String startName = "pn";								//查询起始参数字段名称
	private String limitName = "rn";								//查询数量参数字段名称
	private int start = 0;											//查询起始
	private int limit = 60;											//每次查询数量
	private int total = 1000;										//总获取数量
	private BlockingQueue<RequestUrl> output;							//请求链接输出队列
	private int overFlags;											//结束标志个数
	private List<String> wordlist;
	
	private Logger logger = Logger.getLogger(BaiduUrlProducer.class);//日志
	public BaiduUrlProducer(BlockingQueue<RequestUrl> o,int total,List wordlist){
		this.output = o;
		this.total = total;
		this.wordlist = wordlist;
	}

	/**
	 * 生成Baidu请求链接
	 */
	public void run(){

		for(int i=0;i<wordlist.size();i++){
			int count = start;
			while(count + defaultPageSize < total + defaultPageSize){
				BaiduUrl b = new BaiduUrl(null,false);
				b.setWord(null);
				b.setStart(count);
				b.setLimit(limit);
				b.setUrl(this.baseUrl +
						this.defaultParam.replaceAll("#", "&") + 
						this.wordName + "=" + 
						wordlist.get(i) + "&" +
						this.startName + "=" + 
						count + "&" + 
						this.limitName + "=" + limit);
				try{
					this.output.put(b);
					System.out.println("Thread ["+Thread.currentThread().getId()+"],Put BaiduUrl["+b.getUrl()+"]");
				}catch(Exception e){
					e.printStackTrace();
				}
				count = count + defaultPageSize;
			}
		}
		
		try{
			this.output.put(new RequestUrl(null,true));	
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
